package com.wxj.book.cms.controller;

import com.github.pagehelper.PageInfo;
import com.wxj.book.cms.common.ServerResponse;
import com.wxj.book.cms.pojo.Content;
import com.wxj.book.cms.pojo.Major;
import com.wxj.book.cms.service.ContentService;
import com.wxj.book.cms.service.MajorService;
import com.wxj.book.cms.vo.ContentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ContentController {
    @Autowired
    private ContentService contentService;
    @Autowired
    private MajorService majorService;

    /**
     * 查询所有的领书
     */
    @RequestMapping("content/getAll")
    public String getAllContent(@RequestParam(value = "pageSize",defaultValue = "20") Integer pageSize,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                Model model) {
        PageInfo<ContentVo> pageInfo = contentService.getAll(pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        // 查询专业列表
        List<Major> list = majorService.getMajor();
        model.addAttribute("list", list);
        return "content";
    }

    /**
     * 更新或者添加
     */
    @PostMapping("content/updateContent")
    @ResponseBody
    public ServerResponse updateContent(Content content) {
        int result = contentService.update(content);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }

    /**
     * 根据id删除
     */
    @RequestMapping("content/deleteById")
    @ResponseBody
    public ServerResponse deleteById(@RequestParam("contentId") Integer contentId) {
        if (contentId == null || contentId.equals("") || contentId.equals(" ")) {
            return ServerResponse.createByErrorMessage("删除失败");
        }
        int result = contentService.deleteById(contentId);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");

    }
}
